import azure.cognitiveservices.speech as speech_sdk
from azure.cognitiveservices.speech import AudioDataStream

speech_key, service_region = "insert_azure_speech_key_here", "eastus"
speech_config = speech_sdk.SpeechConfig(subscription=speech_key, region=service_region)
audio_config = speech_sdk.audio.AudioOutputConfig(use_default_speaker=True)


def text2speech(_content, _voice_name, _file_name):
    speech_config.speech_synthesis_voice_name = _voice_name
    audio_config = speech_sdk.audio.AudioOutputConfig(filename=_file_name)
    speech_synthesizer = speech_sdk.SpeechSynthesizer(speech_config=speech_config, audio_config=audio_config)
    result = speech_synthesizer.speak_text_async(_content).get()

    if result.reason == speech_sdk.ResultReason.SynthesizingAudioCompleted:
        print("Speech synthesized to speaker for text [{}]".format(_content))
        stream = AudioDataStream(result)
        stream.save_to_wav_file(_file_name)
    elif result.reason == speech_sdk.ResultReason.Canceled:
        cancellation_details = result.cancellation_details
        print("Speech synthesis canceled: {}".format(cancellation_details.reason))
        if cancellation_details.reason == speech_sdk.CancellationReason.Error:
            if cancellation_details.error_details:
                print("Error details: {}".format(cancellation_details.error_details))
        print("Did you update the subscription info?")


if __name__ == "__main__":
    text2speech("hello,where are you come from", "en-US-AriaNeural", "speech/test.mp3")